package com.zhangsun.system.service.impl;

import com.zhangsun.common.bcrypt.BCryptPasswordEncoder;
import com.zhangsun.expection.BusinessException;
import com.zhangsun.service.JwtService;
import com.zhangsun.system.component.SystemComponent;
import com.zhangsun.system.dto.UserDto;
import com.zhangsun.system.entity.ResourceEntity;
import com.zhangsun.system.entity.RoleEntity;
import com.zhangsun.system.entity.UserEntity;
import com.zhangsun.system.service.LoginService;
import com.zhangsun.system.service.ResourceService;
import com.zhangsun.system.service.RoleService;
import com.zhangsun.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登陆服务
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private JwtService jwtService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private SystemComponent systemComponent;

    @Override
    public UserDto login(String userNo, String password) {
        UserEntity userEntity = userService.findByUserNo(userNo);
        if (userEntity == null) {
            throw new BusinessException("该用户不存在");
        }

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(password, userEntity.getPassword())) {
            throw new BusinessException("用户名或密码不正确");
        }

        UserDto userResult = new UserDto();
        userResult.setUserId(userEntity.getId());
        userResult.setUserNo(userEntity.getUserNo());
        userResult.setName(userEntity.getName());
        userResult.setMobile(userEntity.getMobile());
        userResult.setToken(jwtService.generateToken(userEntity.getUserNo(), userEntity.getPassword()));

        // 角色
        List<RoleEntity> roleList = roleService.findRolesByUser(userEntity.getId());
        userResult.setRoles(systemComponent.getRoles(roleList));

        // 权限
        List<ResourceEntity> resourceList = resourceService.findResourcesByRoles(roleList, userEntity.getId());
        userResult.setPermissions(systemComponent.getPermissions(resourceList));
        userResult.setMenus(systemComponent.getResourceTree(resourceList, true));
        return userResult;
    }

}
